<?php
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2017/2/5 11:09
 * @copyright   WuHan HuQi Technology Co.,Ltd.
 * @url         http://cnhuqi.com
 */

use Wechat\Loader;

class Share extends WX_Controller
{
    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        // 授权登录
        $params = [];
        $params['goodsId'] = $this->input->get('goodsId');
        $params['puserid'] = $this->input->get('puserid');

        if (empty($params['puserid'])) {
            show_404();
            exit;
        }

        $key = md5(microtime(true) . uniqid());
        $this->cache->redis->save($key, $params);

        $callback = WX_URL . '/share/callback';
        $oauth = Loader::get('oauth');
        $url = $oauth->getOauthRedirect($callback, $key, 'snsapi_userinfo');
        redirect($url);
        exit;
    }

    /**
     * 分享后的回调
     */
    public function callback()
    {
        $token = Loader::get('oauth');
        $return = $token->getOauthAccessToken();
        if (empty($return)) {
            echo $token->errMsg;
            exit;
        }

        $openId = value($return, 'openid');
        $paramsKey = $this->input->get('state');

        $params = $this->cache->redis->get($paramsKey);
        if (empty($params)) {
            show_404();
            exit;
        }

        $this->load->model('wx/user/Social_Model', 'social');
        $user = $this->social->checkUserRegist($openId);
        $userId = 0;
        if ($user) {
            $this->social->updateLoginTime($openId);
            $userId = $user['userid'];
        } else {
            // 保存用户信息
            $wechatUser = Loader::get('user');
            $user = $wechatUser->getOauthUserInfo($openId, $return['access_token']);
            if ($user) {
                $this->social->saveUserInfo($user);
                $userId = $this->social->getSaveUserId();
                $this->social->saveRelationShip($userId, $params);
            }
        }

        if (empty($userId)) {
            show_404();
            exit;
        }

        $this->session->set_userdata('openId', $openId);
        $this->session->set_userdata('userid', $userId);
        $redirect = WX_URL . '/detail?id=' . $params['goodsId'];
        redirect($redirect);
    }

    /**
     * 从微信获取用户资料
     * @param $openId
     * @return array|bool
     */
    private function _getUserInfo($openId)
    {
        $user = Loader::get('user');
        $user = $user->getOauthUserInfo();
        return $user->getUserInfo($openId);
    }
}
